import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, PixelRatio, ScrollView, Alert, TouchableOpacity, Image, StatusBar } from 'react-native';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { Button } from '../../../components/form/button';
import { Common } from '../../../component/common/Common.js';
import { GLOBAL, NAVIGATIONS } from '../../../config/global';
import { betweenLayout } from '../create/_components/common';
import { purchaseTag, saleTag, currency } from '../create/_components/common';
import { style } from '../../../theme/style';
import { API, API_GENERATE } from '../../../config/api';
import { StateLightBox } from '../../../component/Store';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import MethodUtil from '../../../utils/MethodUtil';
import { NavigationActions } from 'react-navigation';
import { ProgressModal } from '../../../components/common/ProgressModal';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import { STORAGE_CONSTANT } from '../../../config/storage';
import StorageHelper from '../../../utils/storageHelper';
import Dictionary from '../../../utils/dictionary';
import { CommonDialog } from '../../../components/common/Dialog'
import { ProductInfoItem } from '../create/_components/ProductInfoItem';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { RelevanceDetailContainer } from './_components/RelevanceDetailContainer';

const scale = GLOBAL.SCALE;
const arrowImg = require('../../../imgs/arrow.png');
let titleImgObj = require('../../../imgs/arrow.png');
const previewModal = {
	delTextHide: true,
	visible: false,
	uri: null,
	picPress: () => { },
	fileId: '',
}
export class SinoNewOrderDetailPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		let { orderId, businessKey, orderType, bizMode, statusName } = navigation.state.params.paramsData || {};
		statusName = statusName || '';
		let title = bizMode == 1 ? '闭口' : orderType === 'P' ? '采购' : '销售';
		title = `新油${title}成交-${statusName}`
		return {
			headerTitle: title,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
			headerRight: null,
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			},
			gesturesEnabled: false  //禁止侧滑返回事件
		}
	};
	constructor(props) {
		super(props);
		console.log('props.navigation.state.params', props.navigation.state.params)
		let { businessKey, formKey, taskId, auditResult, orderId, isCancel, status } = props.navigation.state.params.paramsData || {};
		this.status = status;
		this.orderId = orderId;
		this.businessKey = businessKey;
		this.formKey = formKey;
		this.taskId = taskId;
		this.auditResult = auditResult;
		this.requesting = false;
		this.isCancel = isCancel || false;
		this.approveIndex = props.navigation.state.params.approveIndex || 0; // 审批页面进来会带一个tab的标记
		this.choice = props.navigation.state.params.choice || {}; // 业务组织
		this.state = {
			refuseModalVisible: false,
			status: 'data',
			POrderInfo: {},//采购
			SOrderInfo: {},//销售
			fee: [], //费用
			goods: [],//商品
			payMethod: [],//付款方式
			showBackOutOrder: false, // 是否显示撤回本单
			showBackOutPush: false, // 是否显示撤回推送
			showCancelBackOutPush: false, // 是否显示取消撤回推送
			showPushAgain: false, // 是否显示重新推送、删除、变更
			purchaseOrderStatus: null, // 是否作废状态 1-作废 2-正常
			purchaseOrderId: '', // 外采订单号
			hideStatusBar: false,
			isSingapore: false,
			cancelType: null,
			otherInfo: {
				beginAddress: '',
				endAddress: '',
				priceTerm: '',
				priceTermDesc: '',
				remark: ''
			},
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '',
				rowDataList: [],
			},
			modalVisible: false,
			tabIndex: 0
		}
		this.currModalObj = {

		}
		this.bizStaffName = '';//分公司
		previewModal.picPress = () => {
			previewModal.visible = false;
			previewModal.uri = null;
			this.setState({ hideStatusBar: false })
		}
		this.isAdjust = false;
		this.isEdit = false;
	}

	async componentWillMount() {
		this.userInfo = await this._getUserInfo();
		this.getOrderInfo();
		this.getUserInfo();
	}

	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
		}
		return userInfo || {};
	}

	getUserInfo = async () => {
		let userRoles = this.userInfo.userRoles;
		if (this.userInfo) {
			this.userId = this.userInfo.userId;
		}
		for (let i = 0; i < userRoles.length; i++) {
			if (userRoles[i].roleCode && userRoles[i].roleCode == 'ROLE_XYCSDD_XJPSW') {
				this.setState({ isSingapore: true })
				return
			}
		}
	}


	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	getOrderInfo = async () => {
		this.setState({ status: 'loading' });
		let responseData = await HTTP.GET(API_GENERATE(API.ZXY_ORDER_INFO), { orderId: this.orderId || this.businessKey });
		this.detailData = responseData;
		this.setState({ status: 'data' });
		let { oppoPurOrderInfoVO, oppoSaleOrderInfoVO, zxyOrderInfoVO, zxyOrderFeeVOs, zxyOrderItemVOs, zxyOrderPayMethodVOs, zxyPurOrderPayMethodVOs, zxySaleOrderPayMethodVOs } = responseData;
		let { POrderInfo, SOrderInfo, fee, goods, payMethod, otherInfo } = this.state;
		console.log('responseData-详情数据', responseData)
		if (!zxyOrderInfoVO) {
			this.tCode = 'SINONEWC';
			this.bizStaffName = oppoSaleOrderInfoVO.bizStaffName;
			this.bizTeamName = oppoSaleOrderInfoVO.bizTeamName;
			this.organName = oppoSaleOrderInfoVO.staffOrganName;
			this.fileId = oppoSaleOrderInfoVO.fileId || '';
			this.statusName = oppoSaleOrderInfoVO.statusName || '';
			this.wc = oppoSaleOrderInfoVO.wc || '';
			POrderInfo = oppoPurOrderInfoVO;
			SOrderInfo = oppoSaleOrderInfoVO;
			payMethod = [];
			zxyPurOrderPayMethodVOs.map((item, index) => {
				payMethod.push({ PPayMethod: item, SPayMethod: zxySaleOrderPayMethodVOs[index] });
			})
			otherInfo.remark = POrderInfo.remark;
			otherInfo.cancelRemark = POrderInfo.cancelRemark;
			otherInfo.beginAddress = POrderInfo.beginAddress;
			otherInfo.endAddress = POrderInfo.endAddress;
			otherInfo.priceTerm = POrderInfo.priceTerm;
			otherInfo.priceTermDesc = POrderInfo.priceTermDesc || '';
			otherInfo.cancelType = POrderInfo.cancelType || '';
			otherInfo.cancelTypeName = POrderInfo.cancelTypeName || '';
			otherInfo.cancelTypeRemark = POrderInfo.cancelTypeRemark || '';

		} else if (zxyOrderInfoVO.orderType === 'P') {
			this.tCode = `SINONEWP`;
			this.bizStaffName = zxyOrderInfoVO.bizStaffName;
			this.bizTeamName = zxyOrderInfoVO.bizTeamName;
			this.organName = zxyOrderInfoVO.staffOrganName;
			this.fileId = zxyOrderInfoVO.fileId || '';
			this.statusName = zxyOrderInfoVO.statusName || '';
			this.wc = zxyOrderInfoVO.wc || '';
			POrderInfo = zxyOrderInfoVO;
			zxyOrderPayMethodVOs.map(item => { payMethod.push({ PPayMethod: item }) })
			otherInfo.remark = POrderInfo.remark;
			otherInfo.cancelRemark = POrderInfo.cancelRemark;
			otherInfo.beginAddress = POrderInfo.beginAddress;
			otherInfo.endAddress = POrderInfo.endAddress;
			otherInfo.priceTerm = POrderInfo.priceTerm;
			otherInfo.priceTermDesc = POrderInfo.priceTermDesc || '';
			otherInfo.cancelType = POrderInfo.cancelType || '';
			otherInfo.cancelTypeName = POrderInfo.cancelTypeName || '';
			otherInfo.cancelTypeRemark = POrderInfo.cancelTypeRemark || '';
		} else if (zxyOrderInfoVO.orderType === 'S') {
			this.tCode = `SINONEWS`;
			this.bizStaffName = zxyOrderInfoVO.bizStaffName;
			this.bizTeamName = zxyOrderInfoVO.bizTeamName;
			this.organName = zxyOrderInfoVO.staffOrganName;
			this.fileId = zxyOrderInfoVO.fileId || '';
			this.statusName = zxyOrderInfoVO.statusName || '';
			this.wc = zxyOrderInfoVO.wc || '';
			SOrderInfo = zxyOrderInfoVO;
			zxyOrderPayMethodVOs.map(item => { payMethod.push({ SPayMethod: item }) })
			otherInfo.remark = SOrderInfo.remark;
			otherInfo.cancelRemark = SOrderInfo.cancelRemark;
			otherInfo.beginAddress = SOrderInfo.beginAddress;
			otherInfo.endAddress = SOrderInfo.endAddress;
			otherInfo.priceTerm = SOrderInfo.priceTerm;
			otherInfo.priceTermDesc = SOrderInfo.priceTermDesc || '';
			otherInfo.cancelType = SOrderInfo.cancelType || '';
			otherInfo.cancelTypeName = SOrderInfo.cancelTypeName || '';
			otherInfo.cancelTypeRemark = SOrderInfo.cancelTypeRemark || '';
			if (zxyOrderInfoVO.companyId == '154i6enqw0viqjhjqdni2jfim') {
				this.getCancelInfo();
			}
		}
		fee = zxyOrderFeeVOs;
		goods = zxyOrderItemVOs;
		otherInfo.profit = this.getProfit(goods);
		// 刷新页面数据可能会改变订单状态
		if (this.statusName) {
			let { paramsData } = this.props.navigation.state.params;
			paramsData.statusName = this.statusName;
			this.props.navigation.setParams({ paramsData })
		}
		/**
		 * sapPushStatus 推送状态
		 * {
		 *   0:未推送
		 *   1:已推送
		 *   2:撤回待审批
		 *   3:审批通过待撤回
		 *   4:推送中
		 * }
		 * sapLockStatus:冻结状态
		 * {
		 *   0:未冻结
		 *   1:已冻结
		 *   2:待冻结
		 *   3:待解冻（待未冻结）
		 * }
		 * status:订单状态
		 * {
		 *   RPT_DRAFT:草稿
		 *   RPT_AUDITING:审批中
		 *   RPT_AUDIT_UNPASS:审批驳回
		 *   EXECUTING:执行中
		 * }
		 */
		let ifStaffPersonal = SOrderInfo.bizStaffId == this.userId || POrderInfo.bizStaffId == this.userId;
		let showBackOutOrder = ifStaffPersonal && (SOrderInfo.status == 'RPT_AUDITING' || POrderInfo.status == 'RPT_AUDITING'); //撤回本单->成交报告审批中
		let showBackOutPush = ifStaffPersonal && (SOrderInfo.status == 'EXECUTING' || POrderInfo.status == 'EXECUTING')
			&& (SOrderInfo.sapPushStatus == '1' || POrderInfo.sapPushStatus == '1')
			&& (SOrderInfo.sapLockStatus == '0' || POrderInfo.sapLockStatus == '0'); //撤回推送、编辑结算价
		let showCancelBackOutPush = ifStaffPersonal && (SOrderInfo.status == 'EXECUTING' || POrderInfo.status == 'EXECUTING')
			&& (SOrderInfo.sapPushStatus == '2' || POrderInfo.sapPushStatus == '2'
				|| SOrderInfo.sapPushStatus == '3' || POrderInfo.sapPushStatus == '3')
			&& (SOrderInfo.sapLockStatus == '1' || POrderInfo.sapLockStatus == '1'); //取消撤回推送
		let showPushAgain = ifStaffPersonal && (SOrderInfo.status == 'EXECUTING' || POrderInfo.status == 'EXECUTING')
			&& (SOrderInfo.sapPushStatus == '0' || POrderInfo.sapPushStatus == '0')
			&& (SOrderInfo.sapLockStatus == '0' || SOrderInfo.sapLockStatus == '1' || POrderInfo.sapLockStatus == '0' || POrderInfo.sapLockStatus == '1'); //重新推送、删除、变更
		let isCANCEL = (SOrderInfo.status == 'EXECUTING' || POrderInfo.status == 'EXECUTING')
			&& (SOrderInfo.sapPushStatus == '2' || POrderInfo.sapPushStatus == '2');//撤单审批
		this.processInstanceId = isCANCEL ? (SOrderInfo.cancelProcessInstanceId || POrderInfo.cancelProcessInstanceId)
			: (SOrderInfo.processInstanceId || POrderInfo.processInstanceId);
		this.setState({
			POrderInfo,//采购
			SOrderInfo,//销售
			fee, //费用
			goods,//商品
			payMethod,//付款方式
			otherInfo,
			showBackOutOrder,
			showBackOutPush,
			showCancelBackOutPush,
			showPushAgain,
			isCANCEL
		})
	}

	// 获取订单是否作废信息
	getCancelInfo = async () => {
		let res = await HTTP.POST(API_GENERATE(API.ZXY_CANCEL_INFO), { orderId: this.orderId });
		if (res && res.status) {
			this.setState({
				purchaseOrderStatus: res.status,
				purchaseOrderId: res.orderId
			})
		}
	}

	getProfit = (goods) => {
		let profit = 0;
		goods.map(item => {
			let sum = MethodUtil.countObj.subtract(Number.parseFloat(item.nakedSalePrice), Number.parseFloat(item.nakedPrice));
			profit += MethodUtil.countObj.multiply(sum, Number.parseFloat(item.quantity));
		})
		return profit;
	}

	gotoOrderList = (page, moreRoute) => {
		let params = {
			isZXY: true,
			typeIndex: 2
		};
		if (page) params.approveIndex = this.approveIndex;
		params.isCancel = this.isCancel;
		this.tCode === 'SINONEWC' ? params.bizMode = 1 : this.tCode === 'SINONEWP' ? params.orderType = 'P' : params.orderType = 'S';
		this.tCode === 'SINONEWC' ? params.statusIndex = 2 : this.tCode === 'SINONEWP' ? params.statusIndex = 0 : params.statusIndex = 1;
		if (GLOBAL.TAB_NAVIGATION.name !== 'HOME') GLOBAL.TAB_NAVIGATION.popToTop();
		navigationSeevice.reset(page || 'OrderListPage', params, moreRoute || []);
	}

	confirm = (remark, operateRemark) => {
		this[`order${this.currModalObj.operate}`](remark, operateRemark);
	}

	openModal = async (operate, maxLength, formKey) => {
		let propsDefaultValue = { 'Reject': '审批驳回', 'Approve': '审批同意' };
		this.currModalObj.operate = operate;
		this.currModalObj.titleText = operate == 'Reject' ? '驳回意见' : operate == 'Approve' ? '审批意见' : '撤回意见';
		this.currModalObj.text = formKey ? '本单涉及高风险外贸授信，请注意确认客户资信情况,是否确认通过？' : null;
		this.currModalObj.maxLength = maxLength;
		this.currModalObj.placeholderText = `限定${maxLength}字…`;
		this.currModalObj.showOperateType = operate == 'BackOutOrder';
		this.currModalObj.propsDefaultValue = propsDefaultValue[operate];
		if (this.currModalObj.showOperateType) {
			this.currModalObj.operateList = await Dictionary.get('EC_OD_CANCEL_TYPE');
		}
		this.setState({ refuseModalVisible: true });
	}
	//订单作废
	orderCancel = async (remark) => {
		let responseData = await HTTP.POST(API_GENERATE(API.ZXY_ORDER_CANCEL), { orderId: this.orderId, remark, corpId: this.choice.corpId || '' });
		if (responseData) {
			this.setState({ refuseModalVisible: false }, () => {
				ToastUtil.showSuccess('已申请作废').then(() => {
					this.gotoOrderList();
				})
			});
		}
	}

	_agreenPress() {
		let { POrderInfo, SOrderInfo, isSingapore } = this.state;
		// 撤销中状态，审批需要跳转页面
		if ((POrderInfo.status == 'RPT_CANCELING' || SOrderInfo.status == 'RPT_CANCELING') && isSingapore) {
			this.props.navigation.navigate('RepealZXYFormPage', {
				tCode: this.tCode,
				orderId: this.orderId,
				formKey: this.formKey,
				businessKey: this.businessKey,
				taskId: this.taskId,
				POrderInfo,
				SOrderInfo,
				processInstanceId: this.processInstanceId,
			})
		} else {
			if (this.formKey != 'ROLE_XYXS_LDHQ' || this.formKey != 'ROLE_XYBK_LDHQ') {
				//风委会审批时双层确认
				this.setState({ modalVisible: true })
			} else this.openModal('Approve', 500);
		}
	}

	//auditResult 1-同意 0-驳回
	//审批驳回
	orderReject = async (remark) => {
		let { paramsData } = this.props.navigation.state.params || {};
		let { processDefinitionKey } = paramsData || {};
		if (this.requesting) return;
		this.requesting = true;
		let responseData = await HTTP.POST(API_GENERATE(API.ZXY_ORDER_APPROVE), {
			businessKey: this.businessKey,
			formKey: this.formKey,
			taskId: this.taskId,
			auditResult: 0,
			remark,
			corpId: this.choice.corpId || '',
			processDefinitionKey: processDefinitionKey || null
		});
		if (responseData) {
			this.setState({ refuseModalVisible: false }, () => {
				this.requesting = false;
				ToastUtil.showSuccess('已驳回').then(() => {
					this.gotoOrderList('SinoNewOilApproveListPage', [{ routeName: 'HomePage' }]);
				})
			});
		} else {
			this.requesting = false;
		}
	}

	//审批通过
	orderApprove = async (remark) => {
		let { paramsData } = this.props.navigation.state.params || {};
		let { processDefinitionKey } = paramsData || {};
		let responseData = await HTTP.POST(API_GENERATE(API.ZXY_ORDER_APPROVE), {
			businessKey: this.businessKey,
			formKey: this.formKey,
			taskId: this.taskId,
			auditResult: 1,
			remark,
			corpId: this.choice.corpId || '',
			processDefinitionKey: processDefinitionKey || null
		});
		if (responseData) {
			this.setState({ refuseModalVisible: false }, () => {
				ToastUtil.showSuccess('已同意').then(() => {
					this.gotoOrderList('SinoNewOilApproveListPage', [{ routeName: 'HomePage' }]);
				})
			});
		}
	}

	//撤回本单
	orderBackOutOrder = () => {
		Alert.alert(
			'提示', `是否撤回本单？`,
			[
				{ text: '取消', },
				{
					text: '确认', onPress: async () => {
						this.setState({ status: 'loading' });
						let res = await HTTP.POST(API_GENERATE(API.ZXY_PROCESS_CANCEL), { orderId: this.orderId });
						if (res) {
							this.setState({ status: 'data' });
							ToastUtil.showSuccess('撤回本单成功').then(() => {
								this.gotoOrderList();
							})
						} else {
							this.setState({ status: 'data' });
						}
					}
				},
			],
		)
	}

	//撤回推送
	orderBackOutPush = async (remark) => {
		let reqUrl = API.ZXY_CANCEL_PUSH;
		let params = {
			orderId: this.orderId
		}
		if (remark) {
			this.setState({ refuseModalVisible: false })
			params.remark = remark;
			this.backoutRequest(reqUrl, params, '撤回推送成功')
		} else {
			Alert.alert('请输入撤回原因！')
		}
	}

	//取消撤回推送
	orderCancelBackOutPush = () => {
		Alert.alert(
			'提示', `是否取消本次撤回推送？`,
			[
				{ text: '取消', },
				{
					text: '确认', onPress: async () => {
						let reqUrl = API.ZXY_CANCEL_PROCESS;
						let params = {
							orderId: this.orderId
						}
						this.backoutRequest(reqUrl, params, '取消撤回推送成功')
					}
				},
			],
		)
	}

	// 撤销请求
	backoutRequest = async (url, params, resText) => {
		this.setState({ status: 'loading' })
		let res = await HTTP.POST(API_GENERATE(url), params);
		this.setState({ status: 'data' })
		if (res) {
			ToastUtil.showSuccess(resText || '操作成功').then(() => {
				this.getOrderInfo();
			})
		}
	}

	// 变更重新提交
	submitAgain = () => {
		let { bizMode, orderType, status, statusName } = this.props.navigation.state.params.paramsData;
		let params = {
			paramsData: {
				orderId: this.orderId,
				orderType,
				bizMode,
				status,
				statusName,
			},
			tCode: bizMode == 1 ? 'SINONEWC' : orderType === 'P' ? 'SINONEWP' : 'SINONEWS',
			corpId: this.choice.corpId,
			submitAgain: true
		}
		this.props.navigation.navigate('SinoNewOrderBaseInfoPage', params)
	}

	//重新推送
	orderPushAgain = () => {
		let reqUrl = API.ZXY_PUSH_AGAIN;
		let params = {
			orderId: this.orderId
		};
		this.backoutRequest(reqUrl, params, '重新推送成功')
	}

	// 作废订单
	deleteOrder = () => {
		Alert.alert(
			'提示', `是否作废此订单？`,
			[
				{ text: '取消', },
				{
					text: '确认', onPress: async () => {
						this.setState({ status: 'loading' });
						let res = await HTTP.GET(API_GENERATE(API.ZXY_DELETE_ORDER), { orderId: this.orderId, corpId: this.choice.corpId });
						if (res) {
							this.setState({ status: 'data' });
							ToastUtil.showSuccess('作废成功').then(() => {
								this.gotoOrderList();
							})
						} else {
							this.setState({ status: 'data' });
						}
					}
				},
			],
		)
	}

	// 是否能调整结算价的标记
	_isAdjust = (SOrderInfo, goods) => {
		let results = false;
		if (this.tCode == "SINONEWS" && SOrderInfo.companyId == '154i6enqw0viqjhjqdni2jfim'
			&& goods[0].priceType == 2 && SOrderInfo.status == 'EXECUTING') {
			results = true;
		}
		return results;
	}

	//保存
	_save = async () => {
		this.isEdit = false;
		this.isAdjust = false;
		console.log('this.detailData', this.detailData)
		let res = await HTTP.POST(API_GENERATE(API.ZXY_ADD_PRICE), this.detailData);
		if (!res.error) {
			ToastUtil.showSuccess('结算价保存成功');
		} else {
			ToastUtil.showWarning('结算价保存失败');
		}
		this.setState({ ls: false })
	}

	// 化销外采订单跳转订单详情
	_goOrderDetail = (purchaseOrderId) => {
		if (!purchaseOrderId) return
		this.props.navigation.navigate('OrderDetailsPage', {
			orderId: purchaseOrderId,
			orderType: 'P',
			choice: this.choice
		})
	}

	_goProcutDetail = (item) => {
		navigationSeevice.navigate('ProductItemDetail', { item, isEdit: this.isEdit, tCode: this.tCode })
	}

	_goMappingDetail = (item) => {
		let { SOrderInfo, fee, goods } = this.state;//测试用，实际不用传
		navigationSeevice.navigate('SinoNewRelevanceDetailPage', { item, SOrderInfo, fee, goods })
	}

	clickTopTabs = (tabIndex) => {
		this.setState({
			tabIndex
		})
	}

	// 选择撤销类型
	changeOperateType = (key, value) => {
		console.log(key, value)
		this.setState({ cancelType: key })
	}

	//获取审批进度
	getApproveProcess = async () => {
		this.setState({ status: 'loading' })
		let paramsOrder = {
			bizId: this.orderId,
			processInstanceId: this.processInstanceId
		};
		let res = await HTTP.GET(API_GENERATE(API.ZXY_APPROVAL_PROCESS), paramsOrder);
		res.forEach(item => {
			if (item.taskName == '领导会签') item.taskName = '风委会成员会签'
		})
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.title = '审批进度';
		lightBoxData.rowDataList = res;
		this.setState({
			lightBoxData,
			status: 'data'
		})
	}

	// 预览变更协议
	previewImg = async () => {
		if (!this.fileId) return;
		this.setState({ status: 'loading' });
		let res = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: this.fileId }, null, 30000);
		if (res && res.absolutePath) {
			previewModal.visible = true;
			previewModal.uri = res.absolutePath;
			this.setState({ status: 'data', hideStatusBar: true });
		} else {
			this.setState({ status: 'data' });
		}
	}


	_getHeight = async (isHeight) => {
		this.scrollview.scrollTo({ x: 0, y: this.isHeight, animated: true });
	}


	render() {
		let { lightBoxData, status, POrderInfo, SOrderInfo, payMethod, fee, goods, otherInfo, refuseModalVisible,
			showBackOutOrder, purchaseOrderStatus, purchaseOrderId, showBackOutPush, showPushAgain, hideStatusBar, isSingapore,
			cancelType, modalVisible, tabIndex, showCancelBackOutPush, isCANCEL } = this.state;
		let feeZero = true;
		let ifXXAudit = this.businessKey && this.tCode === 'SINONEWS' && this.status == 'RPT_AUDITING';//XX新油审批中
		let ifWC = purchaseOrderStatus && purchaseOrderId; //XX新油审批
		let isHX = SOrderInfo.companyId == '154i6enqw0viqjhjqdni2jfim';//XX化销客户
		let isVatRateDutyRate = this.tCode === 'SINONEWP' || (this.tCode === 'SINONEWS' && isHX);//是否显示增值税

		return (
			<View style={{ flex: 1 }}>
				<StatusBar
					barStyle={hideStatusBar ? 'dark-content' : 'light-content'}
					backgroundColor={hideStatusBar ? '#fff' : style.color.themeColor}
				/>
				{/* XX新油审批新增头部tab,可查看绑定信息-tabIndex==1 */}
				{
					ifXXAudit ?
						<View style={styles.topTabsView}>
							<Text style={[styles.topTabsText, !tabIndex ? styles.topTabsTextActive : null]} onPress={() => { this.clickTopTabs(0) }}>交易信息</Text>
							<Text style={[styles.topTabsText, tabIndex ? styles.topTabsTextActive : null]} onPress={() => { this.clickTopTabs(1) }}>绑定信息</Text>
						</View> : null
				}
				<ScrollView ref={(element) => this.scrollview = element}>
					{
						!tabIndex ?
							<View style={{ backgroundColor: '#F4F7FE' }}>
								{/* 订单已作废提示 */}
								<View style={styles.headerInfo}>
									<Text>{this.tCode === 'SINONEWP' ? POrderInfo.orderId : SOrderInfo.orderId}</Text>
									<View style={{ flexDirection: 'row', alignItems: 'center' }}>
										{
											isCANCEL ? (
												<View style={styles.backoutIcon}>
													<Text style={{ color: '#fff', fontSize: 11 * scale }}>撤</Text>
												</View>
											) : null
										}
										<Text style={{ color: style.color.themeColor }} onPress={() => {
											this.getApproveProcess(isCANCEL);
										}}>查看审批流程</Text>
									</View>
								</View>

								{/* 外采订单 */}
								{
									ifWC ? (
										<View style={styles.orderTips}>
											<View style={{ flexDirection: 'row', justifyContent: 'flex-start' }}>
												<Text>关联化销外采订单</Text>
												{
													purchaseOrderStatus == 1 ? <Text style={{ color: 'red' }}>（已作废）</Text> : <Text >（正常）</Text>
												}
											</View>
											<TouchableOpacity activeOpacity={.8} onPress={() => { this._goOrderDetail(purchaseOrderId) }}>
												<Text style={{ color: style.color.themeColor }}>{purchaseOrderId}</Text>
											</TouchableOpacity>
										</View>
									) : null
								}

								<View style={{ paddingTop: 8 * scale, paddingBottom: 5 * scale }}>
									{this.tCode !== 'SINONEWS' ? betweenLayout('供应商', POrderInfo.companyName, { nofixLeft: true }) : null}
									{this.tCode !== 'SINONEWP' ? betweenLayout('客户名称', SOrderInfo.companyName, { nofixLeft: true }) : null}
									{this.tCode == 'SINONEWP' ? betweenLayout('采购给/部门', POrderInfo.organName, { nofixLeft: true }) : null}
									{betweenLayout('长约类型', SOrderInfo.longTermName || POrderInfo.longTermName, { nofixLeft: true })}
								</View>

								<View style={{ backgroundColor: '#FFFFFF' }}>
									<View style={styles.rowSpaceBetween}>
										<Text style={styles.firstTitle}>商品信息</Text>
										{this.tCode == 'SINONEWS' && SOrderInfo.sourceChannel == '4' && isHX ?
											<Text style={[styles.firstTitle, styles.firstTitleBtn]}
												onPress={() => { navigationSeevice.navigate('SinoNewThrowDetailPage', { SOrderInfo, purchaseOrderId }) }}>【查看抛单信息】</Text>
											: null}
									</View>
									{
										goods && goods.map((item, index) => {
											return (
												<ProductInfoItem
													key={index}
													tCode={this.tCode}
													data={{ item, index }}
													isAdjust={this.isAdjust}
													isEdit={this.isEdit}
													isVatRateDutyRate={isVatRateDutyRate}
													itemRightComponent={() => {
														//XX美金销售 && 非转单SOrderInfo.sourceChannel!=='4'
														if (this.tCode == 'SINONEWS' && SOrderInfo.sourceChannel !== '4' && !ifXXAudit) {
															return <Text style={{ color: style.color.themeColor, fontSize: 12 * scale }}>【查看关联】</Text>
														}
													}}
													itemPress={(item, index) => {
														if (this.tCode == 'SINONEWS' && SOrderInfo.sourceChannel !== '4' && !ifXXAudit) {
															//XX && 非转单 && 非审批--> 查看关联
															navigationSeevice.navigate('SinoNewRelevanceDetailPage', { item, SOrderInfo, fee, goods })
														}
													}}
													onChangeText={(item, index) => {
														this.detailData.zxyOrderItemVOs[index] = item;
														this.setState({ ls: true })
													}}
													getHeight={(height) => {
														this.isHeight = height;
													}}
												/>
											)
										})}
								</View>

								<View style={styles.itemBlock}>
									<Text style={styles.firstTitle}>交易信息</Text>
									{betweenLayout('贸易条件', otherInfo.priceTerm === 'OTHER' ? otherInfo.priceTermDesc : otherInfo.priceTerm)}
									{payMethod && payMethod.map((item, index) => {
										let { PPayMethod, SPayMethod } = item;
										return (<View key={index}>
											{PPayMethod ? <View>
												{betweenLayout('付款方式', PPayMethod.payMethodName, { tag: this.tCode === 'SINONEWC' || this.tCode === 'SINONEWP' ? purchaseTag : null })}
												{betweenLayout('比例', `${PPayMethod.paymentRatio}%`, { fontSize: 12 })}
												{betweenLayout('期限', PPayMethod.paymentDays, { fontSize: 12 })}
											</View> : null}
											{SPayMethod ? <View>
												{betweenLayout('付款方式', SPayMethod.payMethodName, { tag: this.tCode === 'SINONEWC' || this.tCode === 'SINONEWS' ? saleTag : null })}
												{betweenLayout('比例', `${SPayMethod.paymentRatio}%`, { fontSize: 12 })}
												{betweenLayout('期限', SPayMethod.paymentDays, { fontSize: 12 })}
											</View> : null}
										</View>)
									})}
									{this.tCode !== 'SINONEWS' ? betweenLayout('最晚装船日期', POrderInfo.deliveryTime, { tag: this.tCode === 'SINONEWC' ? purchaseTag : null }) : null}
									{this.tCode !== 'SINONEWP' ? betweenLayout('最晚装船日期', SOrderInfo.deliveryTime, { tag: this.tCode === 'SINONEWC' ? saleTag : null }) : null}
									{betweenLayout('出库地', otherInfo.beginAddress, { tag: this.tCode === 'SINONEWC' ? purchaseTag : null })}
									{betweenLayout('目的港', otherInfo.endAddress, { tag: this.tCode === 'SINONEWC' ? saleTag : null })}
								</View>

								<View style={styles.itemBlock}>
									<Text style={styles.firstTitle}>费用预估</Text>
									{fee.map((item, index) => {
										if (item.feeAmt || item.feeAmt === 0) feeZero = false;
										return <View key={index}>
											{item.feeAmt || item.feeAmt === 0 ? betweenLayout(item.logisticFundTypeName, `${item.feeAmt} ${item.currencyName}`) : null}
										</View>
									})}
									{feeZero ? <Text style={{ paddingLeft: 24 * scale }}>无</Text> : null}
									{this.tCode === 'SINONEWC' ?
										<View style={{ height: 30 * scale, flexDirection: 'row-reverse' }}>
											<Text style={{ lineHeight: 30 * scale, paddingRight: 24.5 * scale }}>美元</Text>
											<View style={{ height: 30 * scale, paddingTop: 4 * scale, paddingBottom: 4 * scale }}>
												{currency(otherInfo.profit, '', { valueColor: style.color.themeColor })}
											</View>
											<Text style={{ lineHeight: 30 * scale }}>销售毛利：</Text>
										</View> : null}
								</View>

								{this.tCode === 'SINONEWC' ? <View style={[styles.itemBlock, { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingRight: 25 * scale }]}>
									<Text style={styles.firstTitle}>品质损耗</Text>
									<Text style={{ fontSize: 14 * scale, color: '#000000' }}>品质数量背对背，我司不承担损耗</Text>
								</View> : null}

								<View style={[styles.itemBlock, { paddingRight: 25 * scale }]}>
									<Text style={styles.firstTitle}>送审备注</Text>
									<Text style={styles.cancelTypeText}>{otherInfo.remark || '无'}</Text>
								</View>

								{
									otherInfo.cancelRemark ? (
										<View style={[styles.itemBlock, { paddingRight: 25 * scale }]}>
											<View style={{ flexDirection: 'row', alignItems: 'center' }}>
												<Text style={styles.firstTitle}>撤销备注</Text>
												<View style={{ marginLeft: 18 * scale }}>
													{
														(this.wc == 1 || isSingapore) ? null : (
															<View>
																{
																	this.fileId ? (
																		<TouchableOpacity activeOpacity={.8} onPress={() => { this.previewImg() }}>
																			<Text style={{ color: '#1495ED' }}>【合同已双签、查看变更协议】</Text>
																		</TouchableOpacity>
																	) : <Text>合同未双签</Text>
																}
															</View>
														)
													}
												</View>
											</View>
											<Text style={styles.cancelTypeText}>{otherInfo.cancelType == 'OTHER' ? otherInfo.cancelTypeRemark : otherInfo.cancelTypeName}{otherInfo.cancelTypeRemark || otherInfo.cancelTypeName ? '：' : ''}{otherInfo.cancelRemark || ''}</Text>
										</View>
									) : null
								}

								<View style={[styles.itemBlock, styles.bizInfoView]}>
									<Text style={styles.firstTitle}>业务员（部门）</Text>
									<Text style={styles.bizStaffNameText}>
										{(this.bizStaffName || this.bizTeamName || this.organName) ? `${this.bizStaffName || '--'} | ${this.bizTeamName || '--'} | ${this.organName || '--'}` : "--"}
									</Text>
								</View>

								<View style={[styles.itemBlock, styles.bizInfoView]}>
									<Text style={styles.firstTitle}>业务组织</Text>
									<Text style={styles.corpNameText}>{this.choice.corpName || '--'}</Text>
								</View>

								{/* 自己操作 */}
								{!this.businessKey ? (
									<View>
										{
											showBackOutOrder ? (
												<View style={[styles.itemBlock, styles.btns]}>
													<Button
														type='outline'
														height={36}
														width={156}
														text={'撤回本单'}
														btnStyle={{ backgroundColor: '#FD0E0E', borderColor: '#FD0E0E' }}
														textStyle={{ color: '#fff' }}
														onPress={() => { this.orderBackOutOrder() }} />
												</View>
											) : null
										}
										{/* 撤回推送 */}
										{
											showBackOutPush ? (
												<View style={[styles.itemBlock, styles.btns]}>
													{this._isAdjust(SOrderInfo, goods) && !this.isAdjust ? <Button type='fill' onPress={() => { this.isAdjust = true; this.isEdit = true; this._getHeight(); this.setState({ ls: true }) }} text='调整结算价' height={36} width={100} btnStyle={styles.mr10} /> : null}
													{this._isAdjust(SOrderInfo, goods) && this.isAdjust ? <Button type='fill' onPress={this._save} text='保存' height={36} width={60} btnStyle={styles.mr10} /> : null}
													<Button
														type='outline'
														height={36}
														width={156}
														text={'撤回推送'}
														btnStyle={{ backgroundColor: '#FD0E0E', borderColor: '#FD0E0E' }}
														textStyle={{ color: '#fff' }}
														onPress={() => { this.openModal('BackOutPush', 500) }} />
												</View>
											) : null
										}
										{/**取消撤回推送 */}
										{
											showCancelBackOutPush ?
												<View style={[styles.itemBlock, styles.btns]}>
													<Button
														type='outline'
														height={36}
														width={156}
														text={'取消撤回推送'}
														btnStyle={{ backgroundColor: '#FD0E0E', borderColor: '#FD0E0E' }}
														textStyle={{ color: '#fff' }}
														onPress={() => { this.orderCancelBackOutPush() }} />
												</View>
												: null
										}
										{/**变更仅支持提交 */}
										{
											showPushAgain ? (
												<View style={[styles.itemBlock, styles.approveBtns]}>
													<Button text='重新推送' height={36} width={156} onPress={() => { this.orderPushAgain() }} />
													{/* <Button type='outline' text='变更' height={36} width={156} onPress={() => { this.submitAgain() }} /> */}
													<Button type='outline' text='作废' height={36} width={156} onPress={() => { this.deleteOrder() }} />
												</View>
											) : null
										}
									</View>
								) : null}
							</View>
							: <RelevanceDetailContainer resultData={{ SOrderInfo, orderItemList: goods }} />
					}
				</ScrollView>

				{/* 审批人员操作 */}
				{
					this.businessKey ?
						<View style={[styles.approveBtnsBlock, { backgroundColor: isCANCEL ? style.color.bgGray : '#fff' }]} >
							{
								isCANCEL ?
									<View style={{ paddingLeft: 20 * scale, paddingBottom: 20 * scale }}>
										<Text style={styles.cancelInfoText}>撤回申请人：{SOrderInfo.cancelStaffName || POrderInfo.cancelStaffName || '-'}</Text>
										<Text style={styles.cancelInfoText}>撤回申请时间：{SOrderInfo.cancelTime || POrderInfo.cancelTime || '-'}</Text>
										<Text style={styles.cancelInfoText}>撤回原因：{SOrderInfo.cancelRemark || POrderInfo.cancelRemark || '-'}</Text>
									</View>
									: null
							}
							<View style={styles.approveBtns}>
								<Button type='fill' text='同意' height={36} width={156} onPress={() => {
									this._agreenPress();
								}} />
								<Button type='outline' text='驳回' height={36} width={156} onPress={() => {
									this.openModal('Reject', 500)
								}} />
							</View>
						</View>
						: null
				}

				{/**风委会双层确认框 */}
				<CommonDialog
					modalVisible={modalVisible}
					title={'提示'}
					text={'本单涉及高风险外贸授信，请注意确认客户资信情况。'}
					confirmBtnText={'确认'}
					onClosePress={() => { this.setState({ modalVisible: false }) }}
					onConfirmPress={() => {
						this.setState({ modalVisible: false }, () => {
							this.openModal('Approve', 500, true)
						})
					}
					} />

				{/**操作弹出输入提示 */}
				<RefuseModal visible={refuseModalVisible}
					placeholderText={this.currModalObj.placeholderText}
					propsDefaultValue={this.currModalObj.propsDefaultValue}
					titleText={this.currModalObj.titleText}
					text={this.currModalObj.text || null}
					btnPress={this.confirm}
					showOperateType={this.currModalObj.showOperateType} // 展示撤销类型
					operateList={this.currModalObj.operateList} // 撤销数据
					changeOperateType={this.changeOperateType} // 选择撤销类型
					selectedOperateType={cancelType} // 当前选中的撤销类型
					maxLength={this.currModalObj.maxLength || 500}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
							showOperateType: false,
							cancelType: null
						});
					}} />

				{/* 图片预览 */}
				<ModalPicDelComponent {...previewModal} />

				{/* 审批流 */}
				<ProgressModal {...lightBoxData} />
				{
					status == 'loading' ?
						<View style={styles.statusStyle}>
							<PageStatusIndex status={status} />
						</View> : null
				}
			</View >)
	}
}

const styles = StyleSheet.create({
	topTabsView: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		padding: 12 * scale
	},
	topTabsText: {
		flex: 1,
		textAlign: 'center',
		color: '#fff',
		opacity: .8
	},
	topTabsTextActive: {
		opacity: 1,
		fontWeight: 'bold'
	},
	firstTitle: {
		fontSize: 16 * scale,
		color: '#000000',
		fontWeight: 'bold',
		paddingTop: 11 * scale,
		paddingBottom: 20 * scale,
		paddingLeft: 24 * scale
	},
	firstTitleBtn: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
		fontWeight: '500'
	},
	itemBlock: {
		paddingTop: 13 * scale,
		paddingBottom: 13 * scale,
		marginTop: 12 * scale,
		backgroundColor: '#FFFFFF'
	},
	btns: {
		alignItems: 'center',
		justifyContent: 'center',
		paddingBottom: 20 * scale,
		marginTop: 0 * scale,
		flexDirection: 'row'
	},
	headerInfo: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		backgroundColor: '#FFFFFF',
		paddingTop: 14 * scale,
		paddingBottom: 17 * scale,
		paddingLeft: 24 * scale,
		paddingRight: 25 * scale,
	},
	backoutIcon: {
		width: 20 * scale,
		height: 20 * scale,
		backgroundColor: '#CD4B4B',
		borderRadius: 20 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		marginRight: 10 * scale
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: '100%',
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	orderTips: {
		backgroundColor: '#fff',
		marginTop: 14 * scale,
		height: 42 * scale,
		paddingLeft: 22 * scale,
		paddingRight: 22 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	approveBtnsBlock: {
		paddingTop: 25 * scale,
		paddingBottom: 13 * scale
	},
	approveBtns: {
		paddingLeft: 24 * scale,
		paddingRight: 25 * scale,
		marginTop: 0 * scale,
		flexDirection: 'row',
		justifyContent: "space-between"
	},
	bizStaffNameText: {
		flexDirection: 'row',
		fontSize: 14 * scale,
		paddingLeft: 24 * scale,
		paddingRight: 130 * scale
	},
	bizInfoView: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingRight: 25 * scale
	},
	corpNameText: {
		fontSize: 14 * scale,
		paddingLeft: 24 * scale,
		lineHeight: 39 * scale
	},
	cancelTypeText: {
		fontSize: 14 * scale,
		paddingLeft: 24 * scale,
		paddingBottom: 4 * scale,
		lineHeight: 22 * scale
	},
	rowSpaceBetween: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	mr10: { marginRight: 10 * scale }
})